﻿using System;
using System.Windows.Forms;
using CharacterTrailLibrary.Impl;
using CharacterTrailLibrary.Interface;
using CharacterTrailLibrary.Persist.BLL.Model;
using CharacterTrailLibrary.Security;
using DevExpress.XtraEditors;
using Telegnosis.Framework.Constants;

namespace CharacterTrailClient.Windows
{
    public partial class FormBomMainEdit : DevExpress.XtraEditors.XtraForm
    {
        private readonly IBom  _bomImpl = new BomImpl();
        private  TBomMainModel _bomMainModel = null;
        private  bool _newProductFlag = true;
        public FormBomMainEdit()
        {
            InitializeComponent();
            _bomMainModel = new TBomMainModel();
            _bomMainModel.ImportDate = DateTime.Now;
            _bomMainModel.ImportId = UserSession.CurrentUser.UserId;
            _bomMainModel.ExtChar4 = UserSession.CurrentUser.UserName;
            LoadStaticDataBind();
            BindingData();
        }

        public void SetNewButtonEnable(bool b)
        {
            this.CmdNewProduct.Enabled = b;
        }

        public FormBomMainEdit(TBomMainModel bomMainModel)
        {
            InitializeComponent();
            _newProductFlag = false;
            if(bomMainModel == null)
            {
                _bomMainModel = new TBomMainModel();
            }
            else
            {
                _bomMainModel = bomMainModel;
            }
          
            LoadStaticDataBind();
            BindingData();
            //LoadMaterialList();
        }

        private void BindingData()
        {
            if (_bomMainModel != null)
            {
                foreach (var control in groupControl1.Controls)
                {
                    if (control is BaseEdit)
                    {
                        var edit = (BaseEdit) control;
                        edit.DataBindings.Clear();
                        edit.DataBindings.Add("EditValue", _bomMainModel, edit.Tag.ToString(),true,DataSourceUpdateMode.OnValidation);
                    }
                }
            }
        }

        private void DataBindDistinctVersion()
        {
            var list = _bomImpl.GetDistinctProductVersion(int.Parse(this.textEditProductItemId.Text.Trim()));
            this.textEditProductVersion.Properties.Items.Clear();
            foreach (var version in list)
            {
                this.textEditProductVersion.Properties.Items.Add(version);
            }
        }

        private void LoadMaterialList()
        {
            if (_bomMainModel != null)
            {
                var list = _bomImpl.GetBomEntryModelsByProduct(int.Parse(this.textEditProductItemId.Text.Trim()),
                                                               this.textEditProductVersion.Text.Trim());
                this.gridControlBomMaterial.DataSource = list;
            }
        }

        private void LoadStaticDataBind()
        {
            if (_newProductFlag)
            {
                //如果是新增，则绑定静态物料数据
                Binding.DataBinder.BindingProductItem(this.gridLookUpEditProductItemNumber, this.textEditProductItemId,
                                                      this.textEditProductItemName);
                this.textEditProductVersion.Properties.ReadOnly = false;
                this.gridLookUpEditProductItemNumber.Properties.ReadOnly = false;
            }
            else
            {
                //如果是修改，则绑定已经存在的产品
                //修改产品，不能修改版本号
                this.textEditProductVersion.Properties.ReadOnly = true;
                this.gridLookUpEditProductItemNumber.Properties.ReadOnly = true;
                Binding.DataBinder.BindingBomMainItem(this.gridLookUpEditProductItemNumber, this.textEditProductItemId,
                                                   this.textEditProductItemName,this.textEditProductVersion);
            }
            Binding.DataBinder.BindingProductItem(this.gridLookUpEditMaterialItemNumber, this.textEditMaterialItemId,
                                                     this.textEditMaterialItemName);
            Binding.DataBinder.BindingProcedure(this.lookUpEditProcedureNo,this.textEditProcedureName);

            gridLookUpEditProductItemNumber.EditValueChanged += new EventHandler(GridLookUpEditProductItemNumberEditValueChanged);
            this.textEditProductVersion.EditValueChanged += new EventHandler(TextEditProductVersionEditValueChanged);
        }

        private void TextEditProductVersionEditValueChanged(object sender, EventArgs e)
        {
            LoadBomMainModel();
        }

        private void GridLookUpEditProductItemNumberEditValueChanged(object sender, EventArgs e)
        {
            DataBindDistinctVersion();
            LoadBomMainModel();
        }

        private void LoadBomMainModel()
        {
            var model = _bomImpl.GetBomMainModel(int.Parse(this.textEditProductItemId.Text.Trim()),
                                                 this.textEditProductVersion.Text.Trim());
            if (model != null)
            {
                _bomMainModel.CheckStatus = model.CheckStatus;
                LoadMaterialList();
            }
          
        }

        private bool ValidateProductAndMaterial()
        {
            if(String.IsNullOrEmpty(this.gridLookUpEditProductItemNumber.Text.Trim()))
            {
                Message.MsgBox.ShowError("请输入产品代码！");
                return false;
            }

            if (String.IsNullOrEmpty(this.textEditProductVersion.Text.Trim()))
            {
                Message.MsgBox.ShowError("请输入产品版本号！");
                return false;
            }

            if (String.IsNullOrEmpty(this.gridLookUpEditMaterialItemNumber.Text.Trim()))
            {
                Message.MsgBox.ShowError("请输入物料代码！");
                return false;
            }

            if (String.IsNullOrEmpty(this.lookUpEditProcedureNo.Text.Trim()))
            {
                Message.MsgBox.ShowError("请输入工序代码！");
                return false;
            }

            if (this.gridLookUpEditMaterialItemNumber.Text.Trim()== this.gridLookUpEditProductItemNumber.Text.Trim())
            {
                Message.MsgBox.ShowError("产品不能包括自己！");
                return false;
            }

            decimal qty = 0;
            if (String.IsNullOrEmpty(this.calcEditQty.Text.Trim()) 
                || ! decimal.TryParse(this.calcEditQty.Text, out qty)
                || qty<1)
            {
                Message.MsgBox.ShowError("请输入正确的物料数量，必须不小于1！");
                return false;
            }
            return true;
        }

        private void CmdAddToMaterial_Click(object sender, EventArgs e)
        {
            try
            {

                if (! ValidateProductAndMaterial())
                {
                    return;
                }
                if(_newProductFlag)
                {
                    var bomEntryModel = new TBomEntryModel();
                    bomEntryModel.EditFlag = Enums.EditFlag.New;
                    //bomEntryModel.Idx = 1;
                    bomEntryModel.Qty = Decimal.Parse(this.calcEditQty.Text);
                    bomEntryModel.MaterialItemId = int.Parse(this.textEditMaterialItemId.Text);
                    bomEntryModel.MaterialItemNumber = this.gridLookUpEditMaterialItemNumber.Text.Trim();
                    bomEntryModel.MaterialItemName = this.textEditMaterialItemName.Text.Trim();
                    bomEntryModel.ProcedureNo = this.lookUpEditProcedureNo.Text;
                    bomEntryModel.ProcedureName = this.textEditProcedureName.Text.Trim();
                    bomEntryModel.ProductItemId = _bomMainModel.ProductItemId;
                    bomEntryModel.ProductItemName = _bomMainModel.ProductItemName;
                    bomEntryModel.ProductItemNumber = _bomMainModel.ProductItemNumber;
                    bomEntryModel.ProductVersion = _bomMainModel.ProductVersion;
                    bomEntryModel.ImportDate = DateTime.Now;
                    bomEntryModel.ImportId = UserSession.CurrentUser.UserId;
                    bomEntryModel.ExtChar4 = UserSession.CurrentUser.UserName;

                    bomEntryModel.EditFlag = Enums.EditFlag.New;

                    _bomImpl.SaveBom(this._bomMainModel, bomEntryModel);
                }
                else
                {
                    var bomEntryModel = new TBomEntryModel();
                    bomEntryModel.EditFlag = Enums.EditFlag.New;
                    //bomEntryModel.Idx = 1;
                    bomEntryModel.Qty = Decimal.Parse(this.calcEditQty.Text);
                    bomEntryModel.MaterialItemId = int.Parse(this.textEditMaterialItemId.Text);
                    bomEntryModel.MaterialItemNumber = this.gridLookUpEditMaterialItemNumber.Text.Trim();
                    bomEntryModel.MaterialItemName = this.textEditMaterialItemName.Text.Trim();
                    bomEntryModel.ProcedureNo = this.lookUpEditProcedureNo.Text;
                    bomEntryModel.ProcedureName = this.textEditProcedureName.Text.Trim();
                    bomEntryModel.ProductItemId = _bomMainModel.ProductItemId;
                    bomEntryModel.ProductItemName = _bomMainModel.ProductItemName;
                    bomEntryModel.ProductItemNumber = _bomMainModel.ProductItemNumber;
                    bomEntryModel.ProductVersion = _bomMainModel.ProductVersion;
                    bomEntryModel.EditFlag = Enums.EditFlag.New;
                    bomEntryModel.ImportDate = DateTime.Now;
                    bomEntryModel.ImportId = UserSession.CurrentUser.UserId;
                    bomEntryModel.ExtChar4 = UserSession.CurrentUser.UserName;

                    _bomImpl.SaveBom(this._bomMainModel, bomEntryModel);
                }
                this.LoadMaterialList();
                DataBindDistinctVersion();
                this.gridLookUpEditMaterialItemNumber.EditValue = null;
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdUpdateMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                var obj = this.gridViewBomMaterial.GetRow(this.gridViewBomMaterial.FocusedRowHandle);
                var bomEntryModel = (TBomEntryModel)obj;
                if (bomEntryModel != null)
                {
                    var bomMainModel = _bomImpl.GetBomMainModel(bomEntryModel.ProductItemId,
                                                                bomEntryModel.ProductVersion);
                    if(bomMainModel .CheckStatus == 1)
                    {
                        Message.MsgBox.ShowError("该产品已经审核，不能修改！");
                        return;
                    }
                    var form = new FormBomMainEditUpdate(bomEntryModel);
                    form.ShowDialog(this);
                    if (form.DialogResult == DialogResult.OK)
                    {
                        this.LoadMaterialList();
                    }
                }
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdDeleteMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                var obj = this.gridViewBomMaterial.GetRow(this.gridViewBomMaterial.FocusedRowHandle);
                var bomEntryModel = (TBomEntryModel)obj;
                if (bomEntryModel != null)
                {
                    if (Message.MsgBox.ShowYesOrNo("确定要删除选定的物料吗？"))
                    {
                        _bomImpl.DeleteBomEntry(bomEntryModel);
                        this.LoadMaterialList();
                    }
                }
            }
            catch (Exception exception)
            {
                Exceptions.ExceptionHandler.ShowException(exception);
            }
        }

        private void CmdNewProduct_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}